<?php


namespace api\app\controller;


use api\app\model\AddressModel;
use api\app\model\GoodsModel;
use api\app\model\IndentModel;
use api\app\validate\Vildate;
use cmf\controller\RestBaseController;
use think\facade\Db;
use think\Request;

class IndentController extends RestBaseController
{
    public function add(Request $request)
    {
        $userid = $request->hello;
        $data = $request->post();


        $trade_no = date('YmdHis') . mt_rand(1111, 9999);
        $gname = GoodsModel::where('id', '=', $data['goods_id'])->find();
        $address = AddressModel::where('id', '=',  $data['address_id'])->find();
        $sku=$gname['info'];
        $goodsku= $this->getGoodsinfo($data['goods_info'],$sku);

        $insert_data = [
            'user_id' => $userid,
            'goods_name' => $gname['name'],
            'goods_info' => json_encode($data['goods_info']),
            'price' => $goodsku['price'],
            'num' => $data['num'],
            'total_price' => $goodsku['price'] * $data['num'],
            'trade_no' => $trade_no,
            'user_name' => $address['name'],
            'user_address' => $address['address'],
            'user_trl' => $address['mobile'],
            'status' => 0,
            'remarks' => $data['remarks'],
            'create_time' => date('Y:m:d H:i:s')
        ];
        $model=new IndentModel();
        $res = $model->save($insert_data);
        if ($res) {
            return success('成功',
                ['order_id' => $trade_no]);
        } else {
            return error('失败');
        }
    }
    public function getGoodsinfo($data,$sku){
        $goodsku=json_decode($sku,true);

        foreach($goodsku as $v){
            $hasSku=true;
            foreach ($data as $attr=>$val){
                if ($goodsku[$attr] != $val){
                    $hasSku =false;
                }
            }
            if($hasSku){
                return $goodsku;
            }else{
                continue;
            }
        }
    }
    public function kdy(){
        $url = "https://api.kdniao.com/Ebusiness/EbusinessOrderHandle.aspx";
        // 应用级别参数
        $requestData = [
            'LogisticCode' => 'JT5275766670107',
        ];
        $requestDataJson = json_encode($requestData);
        $apiKey = '7f61a1de-0d5e-44be-af1b-e8fb8c5be99f';
        $sign = urlencode(base64_encode(md5( $requestDataJson.$apiKey )));
        $param = [
            'RequestData' => $requestDataJson,
            'RequestType' => 8002,
            'EBusinessID' => 1855247,
            'DataSign' => $sign,
            'DataType' => 2,
        ];
        $res = $this->curlRequest('POST', $url, 'form', $param);
        if ($res) {
            $this->success('查询成功', $res);
        } else {
            $this->error('查询失败');
        }



    }
    // CURL
    function curlRequest($type, $url, $contentType, $data = [], $timeout = 60)
    {
        try {
            $type = strtoupper($type);
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_URL, $url); // 设置请求链接
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 不直接输出页面
            curl_setopt($curl, CURLOPT_HEADER, 0); // 获取响应头向下
            curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);   // 请求超时时间，单位：秒
            curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1');
            if (substr($url, 0, 5) == 'https') {
                // 自动判断是否是 https 提交
                curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
                // https请求，不验证证书和 hosts
                curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
            }
            // 判断 Content-Type 类型
            if ($contentType == 'json') {
                curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type:application/json']);
            }
            if ($contentType == 'form') {
                curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type:application/x-www-form-urlencoded']);
            }
            switch ($type) {
                case "GET" :
                    curl_setopt($curl, CURLOPT_HTTPGET, true);
                    curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
                    break;
                case "POST":
                    curl_setopt($curl, CURLOPT_POST, true);
                    if ($contentType == 'json') {
                        curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
                    }
                    if ($contentType == 'form') {
                        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
                    }
                    break;
            }
            $result = curl_exec($curl);
            $err_code = curl_errno($curl);
            $curlInfo = curl_getinfo($curl);
            curl_close($curl);
            if ($err_code) {
                return ['status' => 'error', 'msg' => 'sendRequestError:' . $err_code];
            }
            if ($curlInfo['http_code'] == 200) {
                return json_decode($result, true);
            }
            return false;
        } catch (\Exception $e) {
            return ['status' => 'error', 'msg' => $e->getMessage()];
        }
    }
}